#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
##    Copyright (C) 2005 manatlan manatlan[at]gmail(dot)com
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published
## by the Free Software Foundation; version 2 only.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##

from common.template import Template
from common.medialib import getFiles

import urllib
import StringIO,os,sys
from exif import process_file

from common import u64dec,u64enc,pageNavigator
try:
    import Image,ImageFile,ImageDraw,ImageFont #pil
except:
    print "Le plugin 'photos' necessite PIL (python-image) (http://www.pythonware.com/products/pil/)"
    sys.exit(-1)

__title__=u"Photos"
__order__=2000
__author__ ="manatlan"
__about__  ="permet de naviguer dans ses photos (utilise l' *exif-thumbnail*)"

DIR=os.path.abspath(u"medias/photos")

class main:
    def index(self,dir=None,page=1):
        global DIR
        if dir:
            dir=u64dec(dir)
        else:
            dir=DIR
        
        cmd={}
        liste = []
        ndirs,nfiles = getFiles(dir,"jpg")
        if dir!=DIR:
            url = u64enc(os.path.dirname(dir))
            liste.append( ("..",None,url))
            cmd["BACK"]="index?dir=%s" %url
        else:
            cmd["BACK"]="/index"

        
        for i in ndirs:
            name = os.path.basename(i)
            liste.append( (name,None,u64enc(i)) )
        for i in nfiles:
            name = os.path.basename(i)
            liste.append( (name,"f",u64enc(i)) )
        
        cmd["PREV"],cmd["NEXT"],navig,items = pageNavigator(liste,12,"index?page=%d&dir="+u64enc(dir),int(page))
            
        if len(nfiles)>0:
            cmd["PLAY"]="show?file="+u64enc(nfiles[0])+"&play=1"
        rep=dir[len(DIR):]
        
        return Template(cmd)


    def show(self,file,play=""):
        fichier = file    # garde en u64 encode !!!
        
        file=u64dec(file)
        ndirs,nfiles = getFiles(os.path.dirname(file),"jpg")
        idx=nfiles.index(file)
        
        dir=os.path.dirname(file)
        nextFile=nfiles[ (idx+1)%len(nfiles) ]
        prevFile=nfiles[ (idx-1)%len(nfiles) ]
        cmd = {"BACK":u"index?dir=%s&page=%d" %(u64enc(dir),1+((len(ndirs)+1+idx)/12)),
            "NEXT":u"show?file="+u64enc(nextFile),
            "PREV":u"show?file="+u64enc(prevFile),
            "max_images_in_cache":0
            }
        if play:
            cmd["PAUSE"] =u"show?file="+u64enc(file)
            cmd["refresh"]=u"3;url=show?file="+u64enc(nextFile)+"&play=1"
            cmd["stop"]=cmd["BACK"]
        else:
            cmd["PLAY"] =u"show?file="+u64enc(nextFile)+"&play=1"
        return Template(cmd)




    #-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
    def mini(self, file):
    #-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
        file=u64dec(file)
        
        # recupere l' "internal EXIF thumbnail" de la jpeg
        fid = open(file, 'rb')
        try:
            exif = process_file(fid)
            tb=exif["JPEGThumbnail"]
            fid.close()
            p = ImageFile.Parser()
            p.feed(tb)
            im = p.close()            
        except:
            im = Image.open("image.png")
            
        if im:
            w,h = im.size
            w,h = fit(float(w),float(h),130,130,1)
            im = im.resize((w,h))
            
            f = StringIO.StringIO()
            im.save(f, "PNG")
            yield "image/png"
            f.seek(0)
            yield f.read()
        else:
            yield None

    #-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
    def image(self, file):
    #-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
        file=u64dec(file)
        im = Image.open(file)
        w,h = im.size
        w,h = fit(float(w),float(h),672.0,528.0,1)
        im = im.resize((w,h))
        f = StringIO.StringIO()
        im.save(f, "GIF")
        yield "image/gif"
        f.seek(0)
        while True:
            buf=f.read(2048)
            if buf=="": break
            yield buf
        f.close()        

def fit(orig_width, orig_height, dest_width, dest_height,zoom):
    if orig_width == 0 or orig_height == 0:
        return 0, 0
    scale = min(dest_width/orig_width, dest_height/orig_height)
    if scale > 1:
        scale = 1
    scale*=zoom
    fit_width = scale * orig_width
    fit_height = scale * orig_height
    return int(fit_width), int(fit_height)

